package cluster

import (
	"context"
	"encoding/json"
	"fmt"
	"time"

	clientv3 "go.etcd.io/etcd/client/v3"
	"xgame.go_server/comm/log"
)

// 注册业务服务器
func RegisterBizServer(
	etcdEndpointArray []string, serverId uint32, bindHost string, bindPort uint32, sjtArray []ServerJobType) {
	etcdCli, err := clientv3.New(clientv3.Config{
		Endpoints:   etcdEndpointArray,
		DialTimeout: 5 * time.Second,
	})

	if nil != err {
		log.Error("%+v", err)
		return
	}

	reportData := &BizServerData{
		ServerId: serverId,
		BindHost: bindHost,
		BindPort: bindPort,
		SjtArray: sjtArray,
	}

	go func() {
		grantResp, _ := etcdCli.Grant(context.TODO(), 10)

		for {
			time.Sleep(5 * time.Second)

			leaseKeepLiveResp, _ := etcdCli.KeepAliveOnce(context.TODO(), grantResp.ID)
			byteArray, _ := json.Marshal(reportData)

			_, _ = etcdCli.Put(
				context.TODO(),
				fmt.Sprintf("xgame.go_server/biz_server_%d", serverId), // xgame.go_server/biz_server_1001
				string(byteArray),
				clientv3.WithLease(leaseKeepLiveResp.ID),
			)
		}
	}()
}
